package me.zhengjie.modules.quartz.task.dingdingUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSON;
import com.qiaofang.common.util.http.HttpClientUitlFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.List;

/**
 * @author junze.liu
 */
@Slf4j
@Component
public class DingdingUtil {

    /**
     * 发送钉钉消息
     * @param dingdingUrl
     * @param secret
     * @param content
     * @param mobileList
     */
    public static void send(String dingdingUrl, String secret, String content, List<String> mobileList) {
        try {
            Long timestamp = System.currentTimeMillis();
            dingdingUrl = dingdingUrl + "&timestamp=" + timestamp + "&sign=" + getSign(timestamp, secret);
            postMsg2DingdingWithAtMobiles(dingdingUrl, content, mobileList);
        } catch (Exception e) {
            log.error("钉钉消息发送失败", e);
        }
    }

    /**
     * 生成签名
     * @param timestamp
     * @param secret
     * @return
     */
    private static String getSign(Long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
    }

    /**
     * 调用钉钉发送接口
     * @param url
     * @param content
     * @param mobileList
     */
    private static void postMsg2DingdingWithAtMobiles(String url, String content, List<String> mobileList) {
        DingDingBody postBody = new DingDingBody();
        postBody.setMsgtype("text");
        postBody.setText(new DingDingContent(content));
        DingDingAt at = new DingDingAt();
        at.setIsAtAll(false);
        if(CollectionUtils.isNotEmpty(mobileList)) {
            at.setAtMobiles(mobileList);
        }
        postBody.setAt(at);
        HttpClientUitlFactory.getOneClientInstance().postWithJson(url, JSON.toJSONString(postBody));
    }
}
